import { createApp,toRaw } from 'vue'
import {createPinia,PiniaPluginContext} from 'pinia'
import './style.css'
import App from './App.vue'
const store = createPinia()


const __piniaKey__:string = 'piniaKey'
type Options = {
key?:string
}
const setStorage = (key:string,value:any) => {
localStorage.setItem(key,JSON.stringify(value))
}
const getStorage = (key:string) => {
return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string): {}
}
const pinaPlugin = (options:Options) => {
//函数柯里化
return (context:PiniaPluginContext) => {
    // console.log(context)
    const { store } = context
    // console.log(store);
    const data = getStorage(`${options ?.key ?? __piniaKey__} - ${store.$id}`)
    // console.log(data)
    store.$subscribe(() => {
        // console.log('change')
        setStorage(`${options ?.key ?? __piniaKey__} - ${store.$id}`,toRaw(store.$state))
    })
    return{
        ...data
    }
}
}
//手写的状态管理库不随页面刷新而重置,需要学习pinia文件夹先注释此处
store.use(pinaPlugin({
    key:'pinia'
}))
createApp(App).use(store).mount('#app')
